package com.ia2014.tp.portal2.integration.converters;

import java.io.StringReader;
import java.io.StringWriter;
 



import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
//import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 



import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import com.ia2014.tp.portal2.log.Log;
 
public class StringToDocumentToString {
 
	private static Logger logger = Logger.getLogger(StringToDocumentToString.class);
	
	/*
	 * String To XML Document	
	 * Document doc = convertStringToDocument(xml_String);
	 * 
	 * XML Document To String
	 * String str = convertDocumentToString(doc);
	 * 
    */
    public final static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        
        try {
            
        	transformer = tf.newTransformer();
        	       	
        	//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        	
        	// below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            
            return output;
            
        } catch (TransformerException e) {
        	
        	logger.error("Error al tratar de Convertir un Document a String");
        	logger.error(e.toString());
        	logger.debug("Stacktrace", e);
        	
        }
         
        return null;
    }
 
    public final static Document convertStringToDocument(String xmlStr) {
        
    	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder;  
        
    	try 
        {  
            builder = factory.newDocumentBuilder();  
            Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) );
            
            return doc;
            
        } catch (Exception e) {  
        	
            logger.error("Error al tratar de Convertir un String a Document.\nString: " + xmlStr);
            logger.error(e.toString());
            logger.debug("Stacktrace", e);
        	
        } 
    	
        return null;
    }
 
}
